package com.duoec.dw.lineage.core.utils;

import com.duoec.dw.lineage.dto.TableLineageDto;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.function.Function;

/**
 * @author xuwenzhen
 */
public class ScriptFormatter {
    private static final String TURN_LINE = "\n";
    private static final String SUFFIX = "\\";

    private ScriptFormatter() {
    }

    public static List<TableLineageDto> wrap(String script, Function<String, List<TableLineageDto>> supplier) {
        List<String> lines = Lists.newArrayList(Splitter.on(TURN_LINE).trimResults().split(script).iterator());

        String sql = Joiner.on(TURN_LINE).join(lines);
        return supplier.apply(sql);
    }

    public static String shSqoopScriptFormat(String sqooopScript) {
        StringBuilder sb = new StringBuilder();
        Splitter.on(TURN_LINE)
                .split(sqooopScript)
                .forEach(line -> {
                    if (line.trim().endsWith(SUFFIX)) {
                        int index = line.lastIndexOf(SUFFIX);
                        sb.append(line, 0, index);
                    } else {
                        if (sb.length() > 0) {
                            sb.append(TURN_LINE);
                        }
                        sb.append(line);
                    }
                });
        return sb.toString();
    }
}
